<?php

/**
 * 
 * @project     : innoTweets 1.0
 * @author      : Dino (DBK)
 * 
 * @package     : Cron Jobs
 * @description : Do database & logs backup and email the backup file
 * 
 */
if (!defined('BASEPATH')) {
  exit('No direct script access allowed');
}

class Cron extends CI_Controller {

  var $temp_folder = NULL;
  var $today = NULL;
  var $is_month_first_day = FALSE;
  var $is_month_last_day = FALSE;
  var $is_week_first_day = FALSE;
  var $is_week_last_day = FALSE;

  public function __construct() {
    parent::__construct();

    // Setting all time to india.
    date_default_timezone_set('Asia/Calcutta');

    // Block request via browser
    $this->load->library('user_agent');
    if ($this->agent->is_browser()) {
      $password = $this->input->get('password', true);
      if ($password != 'inno@tweets') {
        system_log('cron_job', 'Cron running blocked due to browser request at ' . date('Y-m-d H:i:s'));
        die('Browser request blocked');
      }
    } else {
      system_log('cron_job', 'Cron successfully start running at ' . date('Y-m-d H:i:s'));
    }

    // Setting temp folder
    $this->temp_folder = FCPATH . 'assets/temp/';
    $this->cache_folder = FCPATH . 'application/cache/';

    // Setting the date values
    $this->set_date_vars();
  }

  /**
   * Function to set date values & flags
   * 
   */
  private function set_date_vars() {

    // Setting todays date
    $this->today = (int) date('dmY');

    // Setting is first day of the month flag
    $this->is_month_start = (boolean) (date('d') == 01) ? TRUE : FALSE;

    // Setting is last day of the month flag
    $this->is_month_end = (boolean) (date('d') == date('t')) ? TRUE : FALSE;

    // Setting is first day of the week flag (Monday)
    $this->is_week_first_day = (boolean) (strtoupper(date('D')) == 'MON') ? TRUE : FALSE;

    // Setting is last day of the week flag
    $this->is_week_last_day = (boolean) (strtoupper(date('D')) == 'SAT') ? TRUE : FALSE;
  }

  /**
   * Init cron
   * 
   * Will run daily at 12:00 AM
   * 
   */
  public function index() {

    // Loading email library
    $this->load->library('email');

    // Clean db every day (Deleting hidden items (status 0))
    $this->clean_db();

    // Update user activity points every day
    $this->update_activity_points();

    // Clean cache folder
    $this->deleteItems($this->cache_folder);

    // Generate db backup every week (Tuesday)
    if ($this->is_week_first_day) {
      $this->generate_db_backup();
    }

    // Generate logs backup every month
    if ($this->is_month_first_day) {
      $this->generate_logs_backup();
    }

    die('done');
  }

  /**
   * Function to clean db
   * Remove tweets with status 0
   * Remvoe polls with status 0
   * Remove albums with status 0
   * Remove events with status 0
   * Remove comments with status 0
   * 
   */
  private function clean_db() {

    // Cleaning tweets
    $query_exec = $this->db->get_where('tweets', array('tweet_status' => 0));
    if ($query_exec == TRUE) {
      foreach ($query_exec->result_array() as $tweet) {
        $this->db->delete('follows', array('follow_tweet_id' => $tweet['tweet_id']));
        $this->db->delete('tweets_reply', array('tweet_reply_tweet_id' => $tweet['tweet_id']));
        $this->db->delete('tweets', array('tweet_id' => $tweet['tweet_id']));
      }
    }

    // Cleaning polls
    $query_exec = $this->db->get_where('polls', array('poll_status' => 0));
    if ($query_exec == TRUE) {
      foreach ($query_exec->result_array() as $poll) {
        $this->db->delete('polls_reply', array('poll_reply_poll_id' => $poll['poll_id']));
        $this->db->delete('polls_options', array('poll_option_poll_id' => $poll['poll_id']));
        $this->db->delete('polls', array('poll_id' => $poll['poll_id']));
        $this->db->delete('likes', array('like_type' => 'poll', 'like_type_id' => $poll['poll_id']));
        $this->db->delete('comments', array('comment_type' => 'poll', 'comment_type_id' => $poll['poll_id']));
      }
    }

    // Cleaning tweet repies
    $this->db->delete('tweets_reply', array('tweet_reply_status' => 0));

    // Cleaning events
    $this->db->delete('events', array('event_status' => 0));

    // Cleaning albums
    $this->db->delete('albums', array('album_status' => 0));

    // Cleaning wall post
    $this->db->delete('wall_posts', array('wall_post_status' => 0));

    // Cleaning comments
    $this->db->delete('comments', array('comment_status' => 0));
  }

  /**
   * Function to generate database backup & send email
   * 
   */
  private function generate_db_backup() {
    $bkp_file = $this->temp_folder . $this->db->database . '_' . $this->today . '.sql';
    $command = "mysqldump --opt -h" . $this->db->hostname . " -u" . $this->db->username . " -p" . $this->db->password . " " . $this->db->database . " > " . $bkp_file;
    @system($command);
    $this->send_email('innoTweets DB : ' . $this->today, 'innoTweets Databse Backup - ' . date('d-m-Y H:i:s'), $bkp_file);
    @unlink($bkp_file);
  }

  /**
   * Function to generate logs backup & send email
   * 
   */
  private function generate_logs_backup() {
    $bkp_file = $this->temp_folder . 'logs' . '_' . $this->today . '.zip';
    $logs_folder = FCPATH . APPPATH . 'logs/';
    $command = "zip -r {$bkp_file} {$logs_folder}";
    @system($command);
    $this->send_email('innoTweets Logs : ' . $this->today, 'innoTweets Logs Backup - ' . date('d-m-Y H:i:s'), $bkp_file);
    @unlink($bkp_file);
  }

  /**
   * Function to update user activity points
   * 
   */
  private function update_activity_points() {
    $this->load->library('user_reputation');
    $get_all_users = $this->user_model->get_all_users();
    if (!empty($get_all_users['result'])) {
      foreach ($get_all_users['result'] as $user) {
        if ($user['user_resigned'] == 0) {
          $user_update_data['user_likes_level'] = (int) $this->user_reputation->init($user['user_id']);
          $this->user_model->update_profile($user['user_id'], $user_update_data);
        }
      }
    }
  }

  /**
   * Function to send email with provided details & attachment
   * 
   */
  private function send_email($subject = NULL, $message = NULL, $attachment = NULL) {
    $this->email->clear(TRUE);
    $this->email->from($this->config->item('smtp_user'), 'innoTweets');
    $this->email->to($this->config->item('smtp_user'));
    $this->email->subject($subject);
    $this->email->set_mailtype("html");
    $this->email->message($message);
    if ($attachment) {
      $this->email->attach($attachment);
    }
    $this->email->send();
  }

  private function deleteItems($path = null) {
    if (!empty($path)) {
      $files = glob($path . '*');
      foreach ($files as $file) {
        if (is_file($file)) {
          unlink($file);
        }
      }
    }
  }

}

?>
